package com.idanchuang.component.redis;

import com.idanchuang.component.redis.util.DRedisLock;
import com.idanchuang.component.redis.util.DRedisLocks;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * @author yjy
 * @date 2019/11/27 14:51
 **/
@Component
public class Runner1 implements CommandLineRunner {

    @Autowired
    private LockService lockService;

    @Override
    public void run(String... args) throws Exception {

        for (int i = 0; i < 10; i++) {
            new Thread(() -> lockService.doSomething()).start();
        }

        lockService.recursion();

        for (int i = 0; i < 10; i++) {
            new Thread2().start();
        }

        for (int i = 0; i < 10; i++) {
            new Thread1().start();
        }

    }

    private static int a = 0;


    public class Thread1 extends Thread {

        @Override
        public void run() {
            DRedisLocks.runWithLock("testa", 10000L, 10000L, () -> {
                int b = a;
                try {
                    Thread.sleep(300L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                a = b + 1;
                System.out.println(a);
                return null;
            });
            DRedisLocks.runWithLock("testa", () -> {
                int b = a;
                a = b + 1;
                System.out.println(a);
            });
        }

    }

    public class Thread2 extends Thread {

        @Override
        public void run() {
            DRedisLock lock = new DRedisLock("testa");
            lock.lock();
            int b = a;
            a = b + 1;
            System.out.println(a);
            lock.unlock();
        }

    }

}
